package com.dongdong.android.framework.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.dongdong.android.framework.base.BaseApplication;
import com.dongdong.android.framework.utils.LogUtil;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.io.File;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dongdong on 2018/3/27.
 */

public class DbHelper extends OrmLiteSqliteOpenHelper {


    /**
     * 数据库名字
     */
    private static String DB_NAME = "android.db";
    /**
     * 数据库版本
     */
    private static int DB_VERSION = 1;

    private static List<Class> dbTables = new ArrayList<>();

    private static boolean isInit = false;

    private static DbHelper instance;


    public static DbHelper getInstance() {
        if (instance == null) {
            synchronized (DbHelper.class) {
                if (instance == null) {
                    assert (isInit);
                    instance = new DbHelper();
                }
            }
        }
        return instance;
    }

    public static boolean isInit() {
        return isInit;
    }

    private DbHelper() {
        super(BaseApplication.getAppContext(), DB_NAME, null, DB_VERSION);
    }

    protected static void initDB(String dbName, int dbVersion, List<Class> tables) {
        DB_NAME = dbName;
        DB_VERSION = dbVersion;
        dbTables.clear();
        if (null != tables) {
            dbTables.addAll(tables);
        }
        isInit = true;
    }

    @Override
    public void close() {
        if (!isInit) {
            return;
        }
        super.close();
        instance = null;
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        // 创建表
        try {
            for (Class dataClass : dbTables) {
                LogUtil.i("onCreate " + dataClass.getSimpleName());
                TableUtils.createTableIfNotExists(connectionSource, dataClass);
            }
        } catch (SQLException e) {
            LogUtil.e(e.toString());
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        LogUtil.w("onUpgrade" + oldVersion + " " + newVersion);
        if (newVersion > oldVersion) {
            for (Class dataClass : dbTables) {
                DatabaseTools.onUpgrade(database, DB_NAME, BaseApplication.getAppContext(),
                        dataClass);
            }
            onCreate(database, connectionSource);
        } else if (newVersion < oldVersion) {
        }
    }
}
